package fr.umlv.versionning;

import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumnModel;

import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.runtime.ObjectIdImpl;

import fr.umlv.authentication.SessionHandler;
import fr.umlv.model.ClientModel;

// TODO: Auto-generated Javadoc
/**
 * The Class VersionningTable.
 */
public class VersionningTable extends JScrollPane{

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/**
	 * Instantiates a new versionning table.
	 *
	 * @param modelVersion the model version
	 * @param doc the doc
	 */
	public VersionningTable(DataVersionTableModel modelVersion, final Document doc) {
		super();
		setName("Versions");
		final JTable tVersion= new JTable(modelVersion);
		tVersion.setDefaultRenderer(JButton.class,new DefaultTableCellRenderer()
		{
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean
					hasFocus, int row, int col) {
				return (JButton)value;
			}});
		tVersion.addMouseListener(new MouseAdapter() {
			private void forwardEventToButton(MouseEvent e) throws IOException {

				TableColumnModel columnModel = tVersion.getColumnModel();
				int column = columnModel.getColumnIndexAtX(e.getX());
				int row    = e.getY() / tVersion.getRowHeight();
				Object value;

				if(row >= tVersion.getRowCount() || row < 0 ||
						column >= tVersion.getColumnCount() || column < 0)
					return;

				value = tVersion.getValueAt(row, column);

				if(!(value instanceof JButton)){
					return;
				}

				Document myDoc = doc.getAllVersions().get(row);
				CmisObject cmisDoc = SessionHandler.getClientSession().getSession().getObject(new ObjectIdImpl(myDoc.getId()));
				ClientModel.openCmisObject(cmisDoc);

				repaint();
			}
			public void mouseClicked(MouseEvent e) {
				try {
					forwardEventToButton(e);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		setViewportView(tVersion);
	}
}
